package com.ruoyi.mes.service.impl;

import java.util.*;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mes.domain.*;
import com.ruoyi.mes.mapper.*;
import com.ruoyi.mes.utils.AgvUtils;
import com.ruoyi.mes.utils.CodeUtils;
import com.ruoyi.mes.vo.product.BomMtrVo;
import com.ruoyi.mes.vo.product.TecProceVo;
import com.ruoyi.mes.vo.qualityinspection.QualityInspectionVo;
import com.ruoyi.mes.vo.wksp.StartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.mes.service.IWkspTaskService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 车间任务Service业务层处理
 *
 * @author LongAndHao
 * @date 2023-04-04
 */
@Service
public class WkspTaskServiceImpl implements IWkspTaskService {

    @Value("${ruoyi.taskCodeLast}")
    private int taskCodeLast;


    @Autowired
    private ProgPlanMapper progPlanMapper;

    @Autowired
    private ProgPlanDetailMapper progPlanDetailMapper;

    @Autowired
    private ProOrderMapper proOrderMapper;

    @Autowired
    private ProInfoServiceImpl proInfoService;

    @Autowired
    private ProInfoMapper proInfoMapper;

    @Autowired
    private WkspTaskMapper wkspTaskMapper;

    @Autowired
    private PickInfoMapper pickInfoMapper;

    @Autowired
    private TaskCartMapper taskCartMapper;

    @Autowired
    private RevokePickServiceImpl revokePickService;

    @Autowired
    private FinishInhouMapper finishInhouMapper;
    @Autowired
    private ProductionLineMapper productionLineMapper;
    @Autowired
    private ProTecMapper proTecMapper;
    @Autowired
    private ProceInfoMapper proceInfoMapper;
    @Autowired
    private ScheduleMapper scheduleMapper;
    @Autowired
    private LocatorInfoMapper locatorInfoMapper;
    @Autowired
    private HouInfoMapper houInfoMapper;


    /**
     * 查询车间任务
     *
     * @param id 车间任务主键
     * @return 车间任务
     */
    @Override
    public WkspTask selectWkspTaskById(Long id) {
        return wkspTaskMapper.selectWkspTaskById(id);
    }

    @Override
    public List<WkspTask> selectWkspTaskList(WkspTask wkspTask) {
        List<WkspTask> wkspTasks = wkspTaskMapper.selectWkspTaskList(wkspTask);
        List<WkspTask> validTasks = new ArrayList<>();  // 用于存储符合条件的任务

        if (wkspTasks != null && !wkspTasks.isEmpty()) {
            for (WkspTask task : wkspTasks) {
                // 计算生产进度
                task.setProductionSchedule((float) task.getWkspReadyQuantity() / task.getWkspPlanQuantity() * 100);
                task.setWkspNoQuantity(task.getWkspPlanQuantity() - task.getWkspReadyQuantity());

                // 查询产品信息
                ProInfo proInfo = proInfoMapper.selectProInfoById(task.getProId());
                task.setProInfo(proInfo);

                // 查询订单信息
                ProgPlanDetail progPlanDetail = progPlanDetailMapper.selectProgPlanDetailById(task.getProgDetailId());
                if (progPlanDetail == null) {
                    continue;  // 如果订单信息为空，跳过该任务
                }

                // 查询产线信息
                ProductionLine productionLine = productionLineMapper.selectProductionLineByLineId(progPlanDetail.getLineId());
                if (productionLine == null) {
                    // 如果产线信息为空，则不显示该任务
                    continue;
                }

                task.setCircleTime(productionLine.getCycleTime());
                task.setLineName(productionLine.getLineName());
                task.setLineId(productionLine.getLineId());

                ProgPlan progPlan = progPlanMapper.selectProgPlanById(progPlanDetail.getProgId());
                if (progPlan == null) {
                    continue;  // 可根据需求选择是否跳过或处理该任务
                }

                ProOrder proOrder = proOrderMapper.selectProOrdersByCodeAndProId(progPlan.getOrderNumber(), task.getProId());
                task.setProOrder(proOrder);

                // 添加符合条件的任务到新的列表中
                validTasks.add(task);
            }
        }
        return validTasks;
    }

    /**
     * 新增车间任务
     *
     * @param wkspTask 车间任务
     * @return 结果
     */
    @Override
    public int insertWkspTask(WkspTask wkspTask) {
        wkspTask.setCreateTime(DateUtils.getNowDate());
        return wkspTaskMapper.insertWkspTask(wkspTask);
    }

    /**
     * 修改车间任务
     *
     * @param wkspTask 车间任务
     * @return 结果
     */
    @Override
    public int updateWkspTask(WkspTask wkspTask) {
        wkspTask.setUpdateTime(DateUtils.getNowDate());
        return wkspTaskMapper.updateWkspTask(wkspTask);
    }

    /**
     * 批量删除车间任务
     *
     * @param ids 需要删除的车间任务主键
     * @return 结果
     */
    @Override
    public int deleteWkspTaskByIds(Long[] ids) {
        return wkspTaskMapper.deleteWkspTaskByIds(ids);
    }

    /**
     * 删除车间任务信息
     *
     * @param id 车间任务主键
     * @return 结果
     */
    @Override
    public int deleteWkspTaskById(Long id) {
        return wkspTaskMapper.deleteWkspTaskById(id);
    }


    /**
     * 领料清单
     *
     * @param id 车间任务id
     * @return
     */
    @Override
    public AjaxResult pickingList(Long id) {
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(id);
        R<BomMtrVo> bomAndMtr = proInfoService.getBomAndMtrByProId(wkspTask.getProId());
        for (MtrInfo mtr : bomAndMtr.getData().getMtrs()) {
            mtr.setMtrQuantity(mtr.getMtrQuantity() * wkspTask.getWkspPlanQuantity());
        }
        return AjaxResult.success(bomAndMtr.getData());
    }

    /**
     * 确认领料
     *
     * @param id 车间任务id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult confirmPicking(Long id) {
        //修改领料状态 已申请
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(id);
        wkspTask.setPickingStatus(1L);
        wkspTaskMapper.updateWkspTask(wkspTask);

        //领料信息
        R<BomMtrVo> bomAndMtr = proInfoService.getBomAndMtrByProId(wkspTask.getProId());
        String pickCode = CodeUtils.PickCodeCreat();
        for (MtrInfo mtr : bomAndMtr.getData().getMtrs()) {
            PickInfo pickInfo = new PickInfo();
            pickInfo.setWkspTaskId(id);
            pickInfo.setPickCode(pickCode);
            pickInfo.setWkspCode(wkspTask.getWkspCode());
            pickInfo.setMtrCode(mtr.getMtrCode());
            pickInfo.setMtrName(mtr.getMtrName());
            pickInfo.setPickQuantity(mtr.getMtrQuantity() * wkspTask.getWkspPlanQuantity());
            pickInfo.setIspicked(0L);//默认未领
            pickInfo.setRemark("测试数据");
            pickInfoMapper.insertPickInfo(pickInfo);
        }
        return AjaxResult.success("领料成功!");
    }


    /**
     * 生成任务卡
     *
     * @param startVo
     * @return
     */
    @Override
    public AjaxResult start(StartVo startVo) {
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(startVo.getId());
        ProgPlanDetail progPlanDetail = progPlanDetailMapper.selectProgPlanDetailById(wkspTask.getProgDetailId());
        ProductionLine productionLine = productionLineMapper.selectProductionLineByLineId(progPlanDetail.getLineId());
        productionLine.setStatus("0");
        productionLineMapper.updateProductionLine(productionLine);
        String lineType = productionLine.getLineType();
        //查找工序
        List<TecProceVo> tecProceVos = proInfoService.getTecProceByProId(wkspTask.getProId()).getData();

        //根据计划生产数量，及拆分数量生成任务卡
        //任务卡编号生成数量：计划生产数量 / 拆分数量 余数 == 0 ？ 结果 ： 结果 + 1
        List<String> codes = new ArrayList<>();
        if(wkspTask.getOperationStatus().equals(0L)){
            //余数
            int remainder = (int) (wkspTask.getWkspPlanQuantity() % startVo.getSplitQuantity());
            if (remainder == 0) {
                for (int i = 0; i < (wkspTask.getWkspPlanQuantity() / startVo.getSplitQuantity()); i++) {
                    String takCardCode = wkspTask.getWkspCode() + "-" + String.valueOf(taskCodeLast++);
                    codes.add(takCardCode);
                }
            } else {
                for (int i = 0; i < (wkspTask.getWkspPlanQuantity() / startVo.getSplitQuantity()) + 1; i++) {
                    String takCardCode = wkspTask.getWkspCode() + "-" + String.valueOf(taskCodeLast++);
                    codes.add(takCardCode);
                }
            }


            if (remainder != 0) {
                for (int i = 0; i < codes.size() - 1; i++) {
                    for (int j = 0; j < startVo.getSplitQuantity(); j++) {
                        TaskCart taskCart = new TaskCart();
                        taskCart.setProgDetailId(wkspTask.getProgDetailId());
                        taskCart.setWkspTaskId(startVo.getId());
                        taskCart.setTakCardCode(codes.get(i));
                        taskCart.setTaskNeedRptNum((long) tecProceVos.size());//需报工次数为工序数
                        taskCart.setTaskReadyRptNum(0L);
                        taskCart.setRptProceSeque(-1L);//默认没有已报工的顺序
                        taskCart.setStartTime(startVo.getStartTime());
                        taskCart.setStatus(1L);//默认生产中
                        taskCart.setOverTime(startVo.getOverTime());
                        taskCart.setRemark("测试数据");
                        taskCartMapper.insertTaskCart(taskCart);
                    }
                }

                for (int i = 0; i < remainder; i++) {
                    TaskCart taskCart = new TaskCart();
                    taskCart.setProgDetailId(wkspTask.getProgDetailId());
                    taskCart.setWkspTaskId(startVo.getId());
                    taskCart.setTakCardCode(codes.get(codes.size() - 1));
                    taskCart.setTaskNeedRptNum((long) tecProceVos.size());//需报工次数为工序数
                    taskCart.setTaskReadyRptNum(0L);
                    taskCart.setRptProceSeque(-1L);//默认没有已报工的顺序
                    taskCart.setStartTime(startVo.getStartTime());
                    taskCart.setStatus(1L);//默认生产中
                    taskCart.setOverTime(startVo.getOverTime());
                    taskCart.setRemark("测试数据");
                    taskCartMapper.insertTaskCart(taskCart);
                }
            } else {
                for (int i = 0; i < codes.size(); i++) {
                    for (int j = 0; j < startVo.getSplitQuantity(); j++) {
                        TaskCart taskCart = new TaskCart();
                        taskCart.setProgDetailId(wkspTask.getProgDetailId());
                        taskCart.setWkspTaskId(startVo.getId());
                        taskCart.setTakCardCode(codes.get(i));
                        taskCart.setTaskNeedRptNum((long) tecProceVos.size());//需报工次数为工序数
                        taskCart.setTaskReadyRptNum(0L);
                        taskCart.setRptProceSeque(-1L);//默认没有已报工的顺序
                        taskCart.setStartTime(startVo.getStartTime());
                        taskCart.setStatus(1L);//默认生产中
                        taskCart.setOverTime(startVo.getOverTime());
                        taskCart.setRemark("测试数据");
                        taskCartMapper.insertTaskCart(taskCart);
                    }
                }
            }

            wkspTask.setOperationStatus(1L);
            wkspTaskMapper.updateWkspTask(wkspTask);

        }

        //生成任务卡后调取小车工具类派遣小车
//        AgvUtils.dispatchAgv();

        if ("0".equals(lineType)) {
            List<Long> num = new ArrayList<>();
            List<TaskCart> taskCarts = taskCartMapper.selectTaskCartByWskpTaskId(startVo.getId());
            if(startVo.isTest() ){
                wkspTask.setWkspReadyQuantity(wkspTask.getWkspReadyQuantity() + 1);
            }
            for (TaskCart taskCart : taskCarts) {
                num.clear(); // 在开始处理新的 taskCart 之前清空 num 列表
                List<ProTec> proTecs = proTecMapper.selectProTecByProId(wkspTask.getProId());
                for (ProTec proTec : proTecs) {
                    ProceInfo proceInfo = proceInfoMapper.selectProceInfoById(proTec.getProceId());
                    num.add(proceInfo.getTimes());
                }
               // 调用独立的工序执行函数
               simulateProcesses(taskCart, num,wkspTask);

                // 判断工作任务是否完成
                if (wkspTask.getWkspPlanQuantity().longValue() == wkspTask.getWkspReadyQuantity().longValue()) {
                    wkspTask.setOperationStatus(2L);
                    progPlanDetail.setDateTime(DateUtils.getNowDate());
                    progPlanDetailMapper.updateProgPlanDetail(progPlanDetail);
                    wkspTaskMapper.updateWkspTask(wkspTask);
                    // 新增产品入库记录
                    FinishInhou finishInhou = new FinishInhou();
                    finishInhou.setWkspTaskId(wkspTask.getId());
                    finishInhou.setWkspCode(wkspTask.getWkspCode());
                    finishInhou.setProId(wkspTask.getProId());
                    finishInhou.setInhouName(SecurityUtils.getLoginUser().getUser().getNickName());
                    finishInhou.setInhouTime(DateUtils.getNowDate());
                    finishInhou.setInhouQuantity(wkspTask.getWkspReadyQuantity());
                    finishInhou.setStatus(1L); // 默认入库
                    finishInhou.setRemark("测试数据");
                    finishInhouMapper.insertFinishInhou(finishInhou);
                }
                productionLine.setStatus("1");
                productionLineMapper.updateProductionLine(productionLine);
            }

    }

        return AjaxResult.success("成功开工!");
    }


    /**
     * 模拟工序的执行
     *
     * @param taskCart 当前任务车
     * @param processTimes 工序时间列表
     */
    private void simulateProcesses(TaskCart taskCart, List<Long> processTimes,WkspTask wkspTask) {
        // 提前查询所有需要的工序时间，避免重复查询
        Long num = proceInfoMapper.selectProceInfoById(12L).getTimes(); // 虚拟六轴机械臂取放时间
        Long num1 = proceInfoMapper.selectProceInfoById(13L).getTimes(); // 虚拟打标机打标时间
        Long num3 = proceInfoMapper.selectProceInfoById(15L).getTimes(); // 龙门取放时间
        Long num4 = proceInfoMapper.selectProceInfoById(11L).getTimes(); // 小车运行时间

        for (Long timeInSeconds : processTimes) {
            try {
                // 根据时间调整逻辑设置新的工序时间
                if (timeInSeconds.equals(43L)) {
                    timeInSeconds = num4 + num3; // 小车运行时间 + 龙门取放时间
                } else if (timeInSeconds.equals(37L)) {
                    timeInSeconds = num; // 虚拟六轴机械臂取放时间
                } else if (timeInSeconds.equals(62L)) {
                    timeInSeconds = num1; // 虚拟打标机打标时间
                }

                // 模拟工序执行，将秒转换为毫秒
                Thread.sleep(timeInSeconds * 1000); // timeInSeconds 是秒
                System.out.println("完成一个工序，暂停了 " + timeInSeconds + " 秒");

            } catch (InterruptedException e) {
                e.printStackTrace(); // 异常处理
            }
            // 更新任务卡的报工进度
            taskCart.setTaskReadyRptNum(taskCart.getTaskReadyRptNum() + 1);
            taskCart.setRptProceSeque(taskCart.getRptProceSeque() + 1);

            // 更新任务卡到数据库
            taskCartMapper.updateTaskCart(taskCart);

        }
        // 从wkspTask中获取之前已累计的合格数量，如果为空则初始化为0
        Long pass = wkspTask.getPass() == null ? 0L : wkspTask.getPass();

// 模拟质检过程
        QualityInspectionVo qualityInspectionVo = simulateVirtualLineInspection();
        if (!qualityInspectionVo.getIs_pass()) {
            // 如果质检未通过，处理不合格产品逻辑（比如将产品放入不合格库）
            System.out.println("质检未通过，处理不合格产品");
            putProductIntoUnqualifiedWarehouse();
        } else {
            // 如果质检通过，处理合格产品逻辑
            System.out.println("质检通过，处理合格产品");
            putProductIntoQualifiedWarehouse();
            // 合格数量累加
            pass++;
        }
// 将累加后的合格数量设置回任务对象中
        wkspTask.setPass(pass);
        taskCart.setStatus(2L);

// 累加准备数量
        wkspTask.setWkspReadyQuantity(wkspTask.getWkspReadyQuantity() + 1);

        wkspTaskMapper.updateWkspTask(wkspTask);
        taskCartMapper.updateTaskCart(taskCart);
    }

    /**
     * 模拟虚拟产线质检过程，每个产品的质检结果有80%的概率通过。
     * 质检时间模拟通过 Thread.sleep 不同的时长。
     */
    private QualityInspectionVo simulateVirtualLineInspection() {
        Random random = new Random();
        boolean isPass = random.nextInt(100) < 80; // 80%概率通过
        QualityInspectionVo qualityInspectionVo = new QualityInspectionVo();
        qualityInspectionVo.setIs_pass(isPass);

        try {
            if (isPass) {
                Thread.sleep(37 * 1000L);  // 质检通过，模拟等待37秒
            } else {
                Thread.sleep(41 * 1000L);  // 质检未通过，模拟等待41秒
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return qualityInspectionVo;
    }

    /**
     * 将产品放入合格产品库
     */
    private void putProductIntoQualifiedWarehouse() {
        Long qualifiedLocatorId = 17L;  // 合格产品库的库位ID

        // 更新库位信息和仓库容量（示例逻辑）
        LocatorInfo locatorInfo = locatorInfoMapper.selectLocatorInfoById(qualifiedLocatorId);
        locatorInfo.setRemainCapacity(locatorInfo.getRemainCapacity() - 1);
        locatorInfoMapper.updateLocatorInfo(locatorInfo);

        HouInfo houInfo = houInfoMapper.selectHouInfoByHouId(locatorInfo.getHouId());
        houInfo.setHouRemainCapacity(houInfo.getHouRemainCapacity() - 1);
        houInfoMapper.updateHouInfo(houInfo);
    }

    /**
     * 将产品放入不合格产品库
     */
    private void putProductIntoUnqualifiedWarehouse() {
        Long unqualifiedLocatorId = 18L;  // 不合格产品库的库位ID

        // 更新库位信息和仓库容量（示例逻辑）
        LocatorInfo locatorInfo = locatorInfoMapper.selectLocatorInfoById(unqualifiedLocatorId);
        locatorInfo.setRemainCapacity(locatorInfo.getRemainCapacity() - 1);
        locatorInfoMapper.updateLocatorInfo(locatorInfo);

        HouInfo houInfo = houInfoMapper.selectHouInfoByHouId(locatorInfo.getHouId());
        houInfo.setHouRemainCapacity(houInfo.getHouRemainCapacity() - 1);
        houInfoMapper.updateHouInfo(houInfo);
    }

    /**
     * 撤回车间任务卡
     *
     * @param id 车间任务id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult revokeTaskCart(Long id) {
        List<TaskCart> taskCarts = taskCartMapper.selectTaskCartByWskpTaskId(id);
        //任务卡是否已有报工： 报工次数
        for (TaskCart taskCart : taskCarts) {
            if (taskCart.getTaskReadyRptNum() !=0){
                return AjaxResult.error("任务卡已报工，无法撤回!");
            }
        }

        //删除任务卡
        for (TaskCart taskCart : taskCarts) {
            taskCartMapper.deleteTaskCartByTaskCardId(taskCart.getTaskCardId());
        }
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(id);
        wkspTask.setOperationStatus(0L);
        wkspTaskMapper.updateWkspTask(wkspTask);

        return AjaxResult.success("撤回成功!");
    }


    /**
     * 删 - 车间任务 (是否已领料)
     * @param id 车间任务id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult deleteWskpTask(Long id) {
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(id);
        //若未申请 则直接删除车间任务
        if (wkspTask.getPickingStatus() == 0){
            wkspTaskMapper.deleteWkspTaskById(id);
        }else if(wkspTask.getPickingStatus() == 1){
            //若已申请,删除领料出库信息，再删车间任务
            List<PickInfo> pickInfos = pickInfoMapper.selectPickInfoByWkspTaskId(id);
            for (PickInfo pickInfo : pickInfos) {
                pickInfoMapper.deletePickInfoById(pickInfo.getId());
            }
            wkspTaskMapper.deleteWkspTaskById(id);
        }else if (wkspTask.getPickingStatus() == 2){
            //若已领料,则返回物料
            revokePickService.revokeMtr(wkspTask);

            wkspTaskMapper.deleteWkspTaskById(id);
        }
        //更改计划明细状态
        ProgPlanDetail progPlanDetail = progPlanDetailMapper.selectProgPlanDetailById(wkspTask.getProgDetailId());
        progPlanDetail.setStatus(0L);
        progPlanDetailMapper.updateProgPlanDetail(progPlanDetail);


        return AjaxResult.success("删除成功!");
    }


    /**
     * 完工入库 (车间任务卡已完工)
     * @param id 车间任务id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult finishInhou(Long id) {
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(id);
        Schedule schedule = scheduleMapper.selectScheduleByScheduleTaskId(id);
        schedule.setStatus(1L);
        scheduleMapper.updateSchedule(schedule);
        //往完工入库表中新增数据
        FinishInhou finishInhou = new FinishInhou();
        finishInhou.setProId(wkspTask.getProId());
        finishInhou.setWkspTaskId(id);
        finishInhou.setInhouName(SecurityUtils.getLoginUser().getUser().getNickName());
        finishInhou.setWkspCode(wkspTask.getWkspCode());
        finishInhou.setInhouQuantity(wkspTask.getWkspReadyQuantity());
        finishInhou.setStatus(0L);//默认未入库
        finishInhouMapper.insertFinishInhou(finishInhou);

        return AjaxResult.success();
    }
    @Override
    public AjaxResult jianting(Long id) {
        List<ProgPlanDetail> progPlanDetails = progPlanDetailMapper.selectProgPlanDetailByLineId(id);

        // 定义一个列表来存储生产中的车间任务 ID
        List<Long> wksTaskIds = new ArrayList<>();

        for (ProgPlanDetail progPlanDetail : progPlanDetails) {
            if (progPlanDetail.getStatus().equals(1L)) {
                WkspTask wkspTask = wkspTaskMapper.selectWkspTaskByProgDetailId(progPlanDetail.getId());

                // 将任务 ID 添加到列表中
                if (wkspTask != null && wkspTask.getOperationStatus().equals( 1L)) {
                    wksTaskIds.add(wkspTask.getId());
                }
            }
        }

        // 返回列表或进行其他处理
        return AjaxResult.success(wksTaskIds);
    }
    public AjaxResult pass(Long id) {
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(id);
        Long quantity = wkspTask.getWkspReadyQuantity();
        Long passCount = wkspTask.getPass();          // 合格数量
        Long defectiveCount = quantity - passCount;   // 不合格数量

        double passRate = quantity == 0 ? 0.0 : (passCount * 100.0 / quantity);

        Map<String, Object> result = new HashMap<>();
        result.put("passRate", passRate);
        result.put("qualifiedCount", passCount);
        result.put("defectiveCount", defectiveCount);

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult start1(StartVo startVo) {
        WkspTask wkspTask = wkspTaskMapper.selectWkspTaskById(startVo.getId());
        ProgPlanDetail progPlanDetail = progPlanDetailMapper.selectProgPlanDetailById(wkspTask.getProgDetailId());
        ProductionLine productionLine = productionLineMapper.selectProductionLineByLineId(progPlanDetail.getLineId());
        String lineType = productionLine.getLineType();
        // 查找工序
        List<TecProceVo> tecProceVos = proInfoService.getTecProceByProId(wkspTask.getProId()).getData();

        // 根据计划生产数量及拆分数量生成任务卡
        List<String> codes = new ArrayList<>();
        if (wkspTask.getOperationStatus().equals(0L)) {
            // 计算余数
            int remainder = (int) (wkspTask.getWkspPlanQuantity() % startVo.getSplitQuantity());
            int cardCount = remainder == 0 ? (int) (wkspTask.getWkspPlanQuantity() / startVo.getSplitQuantity())
                    : (int) (wkspTask.getWkspPlanQuantity() / startVo.getSplitQuantity()) + 1;
            for (int i = 0; i < cardCount; i++) {
                String taskCardCode = wkspTask.getWkspCode() + "-" + String.valueOf(taskCodeLast++);
                codes.add(taskCardCode);
            }

            if (remainder != 0) {
                // 前面的任务卡，每个任务卡创建 startVo.getSplitQuantity() 张任务卡
                for (int i = 0; i < codes.size() - 1; i++) {
                    for (int j = 0; j < startVo.getSplitQuantity(); j++) {
                        TaskCart taskCart = new TaskCart();
                        taskCart.setProgDetailId(wkspTask.getProgDetailId());
                        taskCart.setWkspTaskId(startVo.getId());
                        taskCart.setTakCardCode(codes.get(i));
                        taskCart.setTaskNeedRptNum((long) tecProceVos.size()); // 需报工次数为工序数
                        taskCart.setTaskReadyRptNum(0L);
                        taskCart.setRptProceSeque(-1L); // 默认没有已报工的顺序
                        taskCart.setStartTime(startVo.getStartTime());
                        taskCart.setStatus(1L); // 默认生产中
                        taskCart.setOverTime(startVo.getOverTime());
                        taskCart.setRemark("测试数据");
                        taskCartMapper.insertTaskCart(taskCart);
                    }
                }
                // 最后一张任务卡创建 remainder 张任务卡
                for (int i = 0; i < remainder; i++) {
                    TaskCart taskCart = new TaskCart();
                    taskCart.setProgDetailId(wkspTask.getProgDetailId());
                    taskCart.setWkspTaskId(startVo.getId());
                    taskCart.setTakCardCode(codes.get(codes.size() - 1));
                    taskCart.setTaskNeedRptNum((long) tecProceVos.size());
                    taskCart.setTaskReadyRptNum(0L);
                    taskCart.setRptProceSeque(-1L);
                    taskCart.setStartTime(startVo.getStartTime());
                    taskCart.setStatus(1L);
                    taskCart.setOverTime(startVo.getOverTime());
                    taskCart.setRemark("测试数据");
                    taskCartMapper.insertTaskCart(taskCart);
                }
            } else {
                // 余数为0时，每个任务卡创建 startVo.getSplitQuantity() 张任务卡
                for (int i = 0; i < codes.size(); i++) {
                    for (int j = 0; j < startVo.getSplitQuantity(); j++) {
                        TaskCart taskCart = new TaskCart();
                        taskCart.setProgDetailId(wkspTask.getProgDetailId());
                        taskCart.setWkspTaskId(startVo.getId());
                        taskCart.setTakCardCode(codes.get(i));
                        taskCart.setTaskNeedRptNum((long) tecProceVos.size());
                        taskCart.setTaskReadyRptNum(0L);
                        taskCart.setRptProceSeque(-1L);
                        taskCart.setStartTime(startVo.getStartTime());
                        taskCart.setStatus(1L);
                        taskCart.setOverTime(startVo.getOverTime());
                        taskCart.setRemark("测试数据");
                        taskCartMapper.insertTaskCart(taskCart);
                    }
                }
            }

            wkspTask.setOperationStatus(1L);
            wkspTaskMapper.updateWkspTask(wkspTask);
        }

        // 生成任务卡后，不再调用模拟报工流程，直接进入后续操作
        if ("0".equals(lineType)) {
            List<TaskCart> taskCarts = taskCartMapper.selectTaskCartByWskpTaskId(startVo.getId());
            // 若处于测试模式，则更新生产数量
            if (startVo.isTest()) {
                wkspTask.setWkspReadyQuantity(wkspTask.getWkspReadyQuantity() + 1);
                wkspTaskMapper.updateWkspTask(wkspTask);
            }
            for (TaskCart taskCart : taskCarts) {
                // 这里移除了 simulateProcesses(taskCart, num, wkspTask) 的调用，
                // 保留后续判断工作任务是否完成的逻辑
                if (wkspTask.getWkspPlanQuantity().longValue() == wkspTask.getWkspReadyQuantity().longValue()) {
                    wkspTask.setOperationStatus(2L);
                    wkspTaskMapper.updateWkspTask(wkspTask);
                    progPlanDetail.setDateTime(DateUtils.getNowDate());
                    progPlanDetailMapper.updateProgPlanDetail(progPlanDetail);
                    // 新增产品入库记录
                    FinishInhou finishInhou = new FinishInhou();
                    finishInhou.setWkspTaskId(wkspTask.getId());
                    finishInhou.setWkspCode(wkspTask.getWkspCode());
                    finishInhou.setProId(wkspTask.getProId());
                    finishInhou.setInhouName(SecurityUtils.getLoginUser().getUser().getNickName());
                    finishInhou.setInhouTime(DateUtils.getNowDate());
                    finishInhou.setInhouQuantity(wkspTask.getWkspReadyQuantity());
                    finishInhou.setStatus(1L); // 默认未入库
                    finishInhou.setRemark("测试数据");
                    finishInhouMapper.insertFinishInhou(finishInhou);
                }
            }
        }

        return AjaxResult.success("成功开工!");
    }


}
